package org.jeecg.modules.flower.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 入库管理
 * @Author: jeecg-boot
 * @Date: 2022-06-09
 * @Version: V1.0
 */
@Api(tags = "入库管理")
@RestController
@RequestMapping("/flower/flowerTagIn")
@Slf4j
public class FlowerTagInController extends JeecgController<TFlowerTagIn2, ITFlowerTagIn2Service> {
    @Autowired
    private ITFlowerTagIn2Service flowerTagInService;

    @Autowired
    private IFlowerTagInfoService flowerTagInfoService;

    @Autowired
    private IFlowerPlantingBaseService flowerPlantingBaseService;

    @Autowired
    private IFlowerPlantingGreenhouseService flowerPlantingGreenhouseService;
    @Autowired
    private IFlowerStorehouseService flowerStorehouseService;
    /**
     * 分页列表查询
     *
     * @param flowerTagIn
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "批量入库管理-分页列表查询")
    @ApiOperation(value = "批量入库管理-分页列表查询", notes = "批量入库管理-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent = "flower/FlowerTagInListQuery")
    public Result<?> queryPageList(TFlowerTagIn2 flowerTagIn,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   @RequestParam(value = "sDate",defaultValue = "") String sDate ,
                                   @RequestParam(value = "eDate",defaultValue = "") String eDate,
                                   HttpServletRequest req) {
//        QueryWrapper<FlowerTagIn> queryWrapper = QueryGenerator.initQueryWrapper(flowerTagIn, req.getParameterMap());
        QueryWrapper<TFlowerTagIn2> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(flowerTagIn.getNo())){
            queryWrapper.eq("no" ,flowerTagIn.getNo());
        }
        if(StringUtils.isNotBlank(flowerTagIn.getSourceBase())){
            queryWrapper.eq("source_base" ,flowerTagIn.getSourceBase());
        }
        if(StringUtils.isNotBlank(flowerTagIn.getVariety())){
            queryWrapper.like("variety" ,flowerTagIn.getVariety());
        } if(StringUtils.isNotBlank(flowerTagIn.getVarietyCode())){
            queryWrapper.like("variety_code",flowerTagIn.getVarietyCode());
        } if(StringUtils.isNotBlank(flowerTagIn.getStorehouse())){
            queryWrapper.eq("storehouse",flowerTagIn.getStorehouse());
        } if(StringUtils.isNotBlank(flowerTagIn.getPackingSpecifications())){
            queryWrapper.eq("packing_specifications" ,flowerTagIn.getPackingSpecifications());
        } if(StringUtils.isNotBlank(flowerTagIn.getFlowerPoleLength())){
            queryWrapper.eq("flower_pole_length" ,flowerTagIn.getFlowerPoleLength());
        } if( flowerTagIn.getTagNum() !=null ){
            queryWrapper.eq("tag_num" ,flowerTagIn.getTagNum());
        } 
        Page<TFlowerTagIn2> page = new Page<TFlowerTagIn2>(pageNo, pageSize);

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        queryWrapper.inSql("mainid","select id  from t_flower_tag_in_main where state=1   ");
        queryWrapper.inSql("storehouse", "SELECT b.code  FROM flower_storehouse b LEFT JOIN flower_storehouse_detail c   on  b.id = c.mainid where c.personid = '"+sysUser.getId()+"'");

        if(StringUtils.isNotBlank(sDate)){
            queryWrapper.ge("sort_time" ,sDate);
        }
        if(StringUtils.isNotBlank(eDate)){
            queryWrapper.le("sort_time",eDate+" 23:59:59");
        }
        queryWrapper.orderByDesc("sort_time","create_time");

        QueryGenerator.installAuthMplus(queryWrapper, TFlowerTagIn2.class);

        IPage<TFlowerTagIn2> pageList = flowerTagInService.page(page, queryWrapper);

//        List<TFlowerTagIn2> records = pageList.getRecords();
//        for (TFlowerTagIn2 record : records) {
//            FlowerPlantingBase base = flowerPlantingBaseService.getById(record.getSourceBase());
//            if (base != null) {
//                record.setBaseName(base.getName());
//            }
//            FlowerPlantingGreenhouse greenhouse = flowerPlantingGreenhouseService.getById(record.getSourceGreenhouse());
//            if (greenhouse != null) {
//                record.setGreenhouseName(greenhouse.getName());
//            }
//        }
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param flowerTagIn
     * @return
     */
/*    @Transactional
    @AutoLog(value = "批量入库管理-添加")
    @ApiOperation(value = "批量入库管理-添加", notes = "批量入库管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody FlowerTagIn flowerTagIn) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        flowerTagIn.setId(uuid);
        if(flowerTagIn.getSortTime() == null){
            flowerTagIn.setSortTime(new Date());
        }

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

        String storehouse = flowerTagIn.getStorehouse();
        if (  StringUtils.isNotBlank(storehouse)) {
            LambdaQueryWrapper<FlowerStorehouse> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FlowerStorehouse::getCode, storehouse);
            FlowerStorehouse one = flowerStorehouseService.getOne(queryWrapper);
            String cost = one.getCost();
            flowerTagIn.setCost( cost );
        }

        flowerTagInService.save(flowerTagIn);
        createTaginfos(flowerTagIn, uuid);
        return Result.ok("添加成功！");
    }*/

  /*  *//**
     * 编辑
     *
     * @param flowerTagIn
     * @return
     *//*
    @AutoLog(value = "批量入库管理-编辑")
    @ApiOperation(value = "批量入库管理-编辑", notes = "批量入库管理-编辑")
    @PutMapping(value = "/edit")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> edit(@RequestBody FlowerTagIn flowerTagIn) {
        String id = flowerTagIn.getId();

        FlowerTagIn flowerTagInOld = flowerTagInService.getById(id);

        //===如果修改数量，则删除台账，重新生成====
        //判断是否已经存在出库，如果存在则不允许修改数量
        LambdaQueryWrapper<FlowerTagInfo> taginfoQuery = new LambdaQueryWrapper<>();
        taginfoQuery.eq(FlowerTagInfo::getInId, id);
        List<FlowerTagInfo> taginfoList = flowerTagInfoService.list(taginfoQuery);
        for (FlowerTagInfo tagInfo : taginfoList) {
            String state = tagInfo.getState();
            if (!"1".equals(state)) {
                log.error("该入库的蔬菜已经出库或删除，不能在修改了！");
                throw new RuntimeException("该入库的蔬菜已经出库或删除，不能在修改了！");
            }
        }
        String storehouse = flowerTagIn.getStorehouse();
        if (  StringUtils.isNotBlank(storehouse)) {
            LambdaQueryWrapper<FlowerStorehouse> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FlowerStorehouse::getCode, storehouse);
            FlowerStorehouse one = flowerStorehouseService.getOne(queryWrapper);
            String cost = one.getCost();
            flowerTagIn.setCost( cost );
        }

        //不存在出库，则删除台账，重新生成
        flowerTagInfoService.remove(taginfoQuery);
        //重新生成入库台账
        createTaginfos(flowerTagIn, id);

        flowerTagInService.updateById(flowerTagIn);
        return Result.ok("编辑成功!");
    }

    *//**
     * 是否可以编辑     *
     *
     * @param id
     * @return
     *//*
    @AutoLog(value = "批量入库管理-是否可以编辑")
    @ApiOperation(value = "批量入库管理-是否可以编辑", notes = "批量入库管理-是否可以编辑")
    @PutMapping(value = "/isedit")
    public Result<?> isedit(@RequestParam(name = "id", required = true) String id) {
        LambdaQueryWrapper<FlowerTagInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FlowerTagInfo::getInId, id);
        lambdaQueryWrapper.ne(FlowerTagInfo::getState, 1);
        List<FlowerTagInfo> list = flowerTagInfoService.list(lambdaQueryWrapper);
        if (list.size() > 0) {
            //存在已经出库的台账数据，所以不能再编辑。
            return Result.ok(false);
        } else
            return Result.ok(true);
    }

    *//**
     * 通过id删除
     *
     * @param id
     * @return
     *//*
    @AutoLog(value = "批量入库管理-通过id删除")
    @ApiOperation(value = "批量入库管理-通过id删除", notes = "批量入库管理-通过id删除")
    @DeleteMapping(value = "/delete")
    @Transactional
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        *//**
         *
         *查找台账数据是否已经出库，如果已经出库则不允许删除，
         * 否则就先删除台账数据，然后在删除入库数据
         *//*
        LambdaQueryWrapper<FlowerTagInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FlowerTagInfo::getInId, id);
        lambdaQueryWrapper.ne(FlowerTagInfo::getState, 1);//不等于入库状态的
        List<FlowerTagInfo> list = flowerTagInfoService.list(lambdaQueryWrapper);
        if (list.size() > 0) {
            //存在已经出库的台账数据，所以不能再编辑。
            throw new RuntimeException("入库的数据已经被出库，不能再进行删除");
        }
        //删除台账数据
        LambdaQueryWrapper<FlowerTagInfo> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(FlowerTagInfo::getInId, id);
        flowerTagInfoService.remove(lambdaQueryWrapper2);
        flowerTagInService.removeById(id);
        return Result.ok("删除成功!");
    }

    *//**
     * 批量删除
     *
     * @param ids
     * @return
     *//*
    @AutoLog(value = "批量入库管理-批量删除")
    @ApiOperation(value = "批量入库管理-批量删除", notes = "批量入库管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @Transactional
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        *//**
         *
         *//*
        LambdaQueryWrapper<FlowerTagInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(FlowerTagInfo::getInId, Arrays.asList(ids.split(",")));
        lambdaQueryWrapper.ne(FlowerTagInfo::getState, 1); //不等于入库状态的
        List<FlowerTagInfo> list = flowerTagInfoService.list(lambdaQueryWrapper);
        if (list.size() > 0) {
            //存在已经出库的台账数据，所以不能再编辑。
            throw new RuntimeException("入库的数据已经被出库，不能再进行删除");
        }
        //删除台账数据
        LambdaQueryWrapper<FlowerTagInfo> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.in(FlowerTagInfo::getInId, Arrays.asList(ids.split(",")));
        flowerTagInfoService.remove(lambdaQueryWrapper2);
        this.flowerTagInService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }
*/
    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "批量入库管理-通过id查询")
    @ApiOperation(value = "批量入库管理-通过id查询", notes = "批量入库管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        TFlowerTagIn2 flowerTagIn = flowerTagInService.getById(id);
        if (flowerTagIn == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(flowerTagIn);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param flowerTagIn
     */
    @RequestMapping(value = "/exportXls")
    @PermissionData(pageComponent = "flower/FlowerTagInListQuery")
    public ModelAndView exportXls(HttpServletRequest request, TFlowerTagIn2 flowerTagIn) {
        return super.exportXls(request, flowerTagIn, TFlowerTagIn2.class, "批量入库管理");
    }

    /**
     * 全部导出excel-按时间段导出
     *
     * @param request
     * @param flowerTagIn
     */
    @RequestMapping(value = "/exportXlsAll")
    @PermissionData(pageComponent = "flower/FlowerTagInListQuery")
    @ApiOperation(value = "批量入库管理-全部导出-按时间段导出", notes = "批量入库管理--全部导出-按时间段导出")
    public ModelAndView exportXlsAll(HttpServletRequest request, TFlowerTagIn2 flowerTagIn,
                                     @RequestParam(value = "sDate",defaultValue = "") String sDate ,
                                     @RequestParam(value = "eDate",defaultValue = "") String eDate) {

        // Step.1 组装查询条件
        QueryWrapper<TFlowerTagIn2> queryWrapper = QueryGenerator.initQueryWrapper(flowerTagIn, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        queryWrapper.orderByAsc("sort_time");
        queryWrapper.orderByAsc("create_time");
        if(StringUtils.isNotBlank(sDate)){
            queryWrapper.ge("sort_time",sDate);
        }
        if(StringUtils.isNotBlank(eDate)){
            queryWrapper.le("sort_time",eDate+" 23:59:59");
        }
        queryWrapper.inSql("storehouse", "SELECT b.code  FROM flower_storehouse b LEFT JOIN flower_storehouse_detail c   on  b.id = c.mainid where c.personid = '"+sysUser.getId()+"'");
        QueryGenerator.installAuthMplus(queryWrapper, TFlowerTagIn2.class);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id",selectionList);
        }
        List<TFlowerTagIn2> list = flowerTagInService.list(queryWrapper);

        String title ="导出";
        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, TFlowerTagIn2.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams  exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
        exportParams.setImageBasePath("upLoadPath");
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS,exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);

        return mv;
    }

}
